package org.example.deadlock;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.example.utils.Sleeper;

/**
 * @author zhengdp
 * @Description 哲学家就餐问题
 * @Date 2022/10/30 19:35
 * @Created by zhengdp
 */
@Slf4j(topic = "c.INFPDeadLock")
public class INFPDeadLock {

    public static void main(String[] args) {
        Chopstick c1 = new Chopstick("1");
        Chopstick c2 = new Chopstick("2");
        Chopstick c3 = new Chopstick("3");
        Chopstick c4 = new Chopstick("4");
        Chopstick c5 = new Chopstick("5");
        new Philosopher("哲学家1",c1,c2).start();
        new Philosopher("哲学家2",c2,c3).start();
        new Philosopher("哲学家3",c3,c4).start();
        new Philosopher("哲学家4",c4,c5).start();
        new Philosopher("哲学家5",c1,c5).start();
    }

    /**
     * 哲学家类
     */
    static class Philosopher extends Thread {
        Chopstick left;
        Chopstick right;

        public Philosopher(String name,Chopstick left,Chopstick right){
            super(name);
            this.left = left;
            this.right = right;
        }

        @Override
        public void run() {
            while(true){
                // 先获取左手，再获取右手筷子
                synchronized (left){
                    synchronized (right){
                        eat();
                    }
                }
            }
        }

        private void eat(){
            log.info("eating ....");
            Sleeper.sleep(1000);
        }
    }

    // 筷子类
    @Data
    @AllArgsConstructor
    static class Chopstick {
        String name;

        @Override
        public String toString() {
            return "筷子{"+name+"}";
        }
    }
}
